/*
	cutter.cpp: Hacky configuration file parsing

	Copyright (c) 2010, James Lee (jbit<at>jbit<dot>net)
	All rights reserved.

	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

	Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
	Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
	Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.	
*/
#define WIN32_LEAN_AND_MEAN		
#define _CRT_SECURE_NO_WARNINGS // C isn't that dangerous...
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "cutter.h"

#define strwind(_s) while (isspace(*(_s))) {_s++;}

void OutputDebugPrintf(const char *format, ...)
{
	char buf[2048];
	va_list ap;
	va_start(ap, format);
	vsnprintf(buf, sizeof(buf), format, ap);
	va_end(ap);
	OutputDebugString(buf);
}

static int cutterParamsReadFlagList(const char *filename, int lineNo, char *line, const char *ident, const char *flagName[], int flags[], size_t count)
{
	for (size_t i=0;i<count;i++)
		flags[i] = 0;

	if (strncmp(line, ident, strlen(ident)))
		return -1;

	line += strlen(ident);

	if (!isspace(*line))
	{
		if (*line=='#' || *line=='\0' || *line=='\r' || *line=='\n')
			return 0;
		else
			return -1;
	}

	strwind(line);
	while (!(*line=='#' || *line=='\0' || *line=='\r' || *line=='\n'))
	{
		int flag = -1;
		for (size_t i=0;i<count;i++)
		{
			if (!strncmp(line, flagName[i], strlen(flagName[i])))
			{
				line += strlen(flagName[i]);
				flag = i;
				break;
			}
		}
		if (flag==-1)
		{
			OutputDebugPrintf("[%s:%d] Malformed %s line (Unrecognised flag: %s)\n", filename, lineNo, ident, line);
			return 0;
		}
		else
		{
			flags[flag]++;
		}

		strwind(line);
	}
	return 1;
}
static int cutterParamsReadIntList(const char *filename, int lineNo, char *line, const char *ident, const char *valueName[], int values[], size_t count)
{
	if (strncmp(line, ident, strlen(ident)))
		return -1;

	line += strlen(ident);

	if (!isspace(*line))
		return -1;

	size_t i;
	for (i=0;i<count;i++)
	{
		strwind(line);
		if (*line=='#' || *line=='\0' || *line=='\r' || *line=='\n')
		{
			OutputDebugPrintf("[%s:%d] Malformed %s line (only %d parameters?!)\n", filename, lineNo, ident, i);
			break;
		}
		if (strncmp(line, valueName[i], strlen(valueName[i])))
		{
			OutputDebugPrintf("[%s:%d] Malformed %s line (expected '%s' as argument %d!!)\n", filename, lineNo, ident, valueName[i], i+1);
			break;
		}
		line+=strlen(valueName[i]);

		char *next = NULL;
		errno = 0;
		values[i] = strtoul(line, &next, 0);
		if (errno)
		{
			OutputDebugPrintf("[%s:%d] Malformed %s line (%s argument has bad number!)\n", filename, lineNo, ident, valueName[i]);
			break;
		}
		line = next;

	}
	if (i<count)
		return 0;

	return i;
}


CutterParams *cutterParamsRead(const char *filename)
{
	FILE *f = fopen(filename, "r");
	if (f==NULL)
	{
		OutputDebugPrintf("[%s] Failed to open (%s)\n", filename, strerror(errno));
		return NULL;
	}

	CutterParams *params = (CutterParams *)malloc(sizeof(CutterParams));
	if (params==NULL)
		return NULL;
	params->blitCount = 0;
	params->configCount = -1;
	params->dllPath[0] = '\0';

	char linebuf[2048];

	int lineNo = 0;
	while (fgets(linebuf, sizeof(linebuf), f))
	{
		lineNo++;
		char *line = linebuf;
		strwind(line);
		if (*line=='#' || *line=='\0' || *line=='\r' || *line=='\n')
			continue;


		static const char *blitName[]  ={"dx:", "dy:", "sx:", "sy:",  "w:",  "h:"};
		static const char *scaleName[] ={"dx:", "dy:", "dw:", "dh:", "sx:", "sy:", "sw:", "sh:"};
		static const char *configName[]={"ROT_NONE","ROT_CW","ROT_FULL","ROT_CCW","LINEAR","AUTO_GAME","AUTO_MENU"};
		int values[16];
		int ret;
		if ((ret=cutterParamsReadIntList(filename, lineNo, line, "blit", blitName, values, 6))>=0)
		{
			if (ret==0)
				continue;

			OutputDebugPrintf("[%s:%d] blit %d,%d -> %d,%d (%dx%d)\n", filename, lineNo, values[0], values[1], values[2], values[3], values[4], values[5]);
			params->blitList[params->blitCount].type = CUTTER_BLIT_NORMAL;
			params->blitList[params->blitCount].dx = values[0];
			params->blitList[params->blitCount].dy = values[1];
			params->blitList[params->blitCount].sx = values[2];
			params->blitList[params->blitCount].sy = values[3];
			params->blitList[params->blitCount].dw = values[4];
			params->blitList[params->blitCount].dh = values[5];
			params->blitList[params->blitCount].sw = params->blitList[params->blitCount].dw;
			params->blitList[params->blitCount].sh = params->blitList[params->blitCount].dh;
			params->blitCount++;
		}
		else if ((ret=cutterParamsReadIntList(filename, lineNo, line, "scale", scaleName, values, 8))>=0)
		{
			if (ret==0)
				continue;

			OutputDebugPrintf("[%s:%d] scale %d,%d (%dx%d) -> %d,%d (%dx%d)\n", filename, lineNo, values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
			params->blitList[params->blitCount].type = CUTTER_BLIT_SCALE;
			params->blitList[params->blitCount].dx = values[0];
			params->blitList[params->blitCount].dy = values[1];
			params->blitList[params->blitCount].dw = values[2];
			params->blitList[params->blitCount].dh = values[3];
			params->blitList[params->blitCount].sx = values[4];
			params->blitList[params->blitCount].sy = values[5];
			params->blitList[params->blitCount].sw = values[6];
			params->blitList[params->blitCount].sh = values[7];
			params->blitCount++;
		}
		else if (!strncmp(line, "dll:", 4))
		{
			line += 4;
			strwind(line);
			char *lineEnd = line + strlen(line) - 1;
		
			// Remove trailing characters
			while (isspace(*lineEnd) || *lineEnd=='\r' || *lineEnd=='\n')
				*(lineEnd--) = '\0';

			OutputDebugPrintf("[%s:%d] dll is '%s'\n", filename, lineNo, line);
			_snprintf(params->dllPath, sizeof(params->dllPath), "%s", line);
		}
		else if ((ret=cutterParamsReadFlagList(filename, lineNo, line, "config", configName, values, 7))>=0)
		{
			// Finish off last config
			if (params->configCount>=0)
				params->configList[params->configCount].blitEnd = params->blitCount;
			params->configCount++;

			params->configList[params->configCount].blitStart = params->blitCount;
			params->configList[params->configCount].rot = CUTTER_ROT_NONE;
			params->configList[params->configCount].flags = 0;

			if (values[0]) params->configList[params->configCount].rot = CUTTER_ROT_NONE;
			if (values[1]) params->configList[params->configCount].rot = CUTTER_ROT_CW;
			if (values[2]) params->configList[params->configCount].rot = CUTTER_ROT_FULL;
			if (values[3]) params->configList[params->configCount].rot = CUTTER_ROT_CCW;
			if (values[4]) params->configList[params->configCount].flags |= CUTTER_FLAG_LINEAR;
			if (values[5]) params->configList[params->configCount].flags |= CUTTER_FLAG_AUTO_GAME;
			if (values[6]) params->configList[params->configCount].flags |= CUTTER_FLAG_AUTO_MENU;

			OutputDebugPrintf("[%s:%d] config%d (rot:%d flags:%x)\n", filename, lineNo, params->configCount, params->configList[params->configCount].rot, params->configList[params->configCount].flags);
		}
		else
		{
			OutputDebugPrintf("[%s:%d] Unknown line (ignored)\n", filename, lineNo);
		}

	}
	params->configList[params->configCount].blitEnd = params->blitCount;
	params->configCount++;
	if (ferror(f))
	{
		OutputDebugPrintf("[%s] I/O error!\n", filename);
		cutterParamsDestroy(params);
		return NULL;
	}

	return params;
}


void cutterParamsDestroy(CutterParams *params)
{
	if (!params)
		return;

	free(params);

}